<template>
  <div class="panel-data">
    <div class="content">
      <el-form
        ref="form"
        class="prop-form"
        label-position="right"
        :model="form"
        :rules="rules"
        label-width="93px"
      >
        <panel-data
          ref="panelDataCommon"
          :config="config"
          :widget-instance-id="widgetInstanceId"
          :data-source-type-options="dataSourceTypeOptions"
          :dataForm="form"
          :do-get-api-data="doGetApiData"
          :is-aurora="isAurora"
        >
          <template #switchDataMapping_after>
            <el-button
              size="default"
              class="btn-sure"
              icon="CirclePlus"
              :disabled="addDisable"
              @click.stop="addNewRow()"
            >{{ $demoi18n('btn.add') }}</el-button>
          </template>
        </panel-data>
      </el-form>
    </div>
  </div>
</template>
<script>
import PanelData from '@/components/panel-data/panel-data-common';
import panelDataBase from '@/mixin/panel-data-base.js';
import EventBus from '@/event-bus/EventBus.js';

export default {
  name: 'HorizontalIndicatorChartPanelData',
  components: { PanelData },
  mixins: [panelDataBase],
  props: ['config', 'widgetInstanceId', 'dataForm', 'dataSourceTypeOptions', 'doGetApiData', 'isAurora'],
  emits: ['updateHorizontalFormNewData'],
  data() {
    const form = JSON.parse(JSON.stringify(this.config.config.data));
    return {
      form,
      addDisable: false,
    };
  },
  computed: {},
  watch: {
    'form.tableData': {
      handler() {
        const len = this.form.tableData.length;
        this.addDisable = len > 30;
      },
    },
  },
  created() {
    EventBus.$on('updateHorizontalFormData', obj => {
      this.updateDatas(obj);
    });
  },
  unmounted() {
    EventBus.$off('updateHorizontalFormData');
  },
  methods: {
    updateDatas(updateObj) {
      const { option, index } = updateObj;
      const len = this.form.tableData.length;

      // 新增
      if (option === 'add') {
        this.form.tableData.push({
          field: `y${len}`,
          mapping: '',
          explain: this.$demoi18n('panelData.explain.value'),
        });
      } else {
        // 删除
        this.form.tableData.splice(index + 1, 1);
        for (let i = index + 1; i < len - 1; i++) {
          this.form.tableData[i].field = `y${i}`;
        }
      }
    },
    addNewRow() {
      const len = this.form.tableData.length;
      const item = {
        field: `y${len}`,
        mapping: '',
        explain: this.$demoi18n('panelData.explain.value'),
      };
      this.addDisable = len > 30;
      this.form.tableData.push(item);
      const data = {
        name: '',
        unit: '',
      };
      EventBus.$emit('updateHorizontalFormNewData', data);
    },
  },
};
</script>
<style lang="less" scoped></style>
